package com.chenyq.rabbitmq.routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;


/**
 *
 * @author chenyq
 * @date 2023/11/28
 */

public class Producer {

    //几个常量
    private static final String DIRECT_EXCHANGE = "directExchange";
    private static final String DIRECT_QUEUE_1 = "directQueue1";
    private static final String DIRECT_QUEUE_2 = "directQueue_2";

    public static void main(String[] args) {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置主机地址
        factory.setHost("127.0.0.1");
        // 设置端口号
        factory.setPort(5672);
        // 设置虚拟主机
        factory.setVirtualHost("/");
        // 设置用户名
        factory.setUsername("admin");
        // 设置密码
        factory.setPassword("123456");
        // 创建连接
        Connection connection = null;
        // 创建通道
        Channel channel = null;
        try {
            // 创建连接
            connection = factory.newConnection();
            // 创建通道
            channel = connection.createChannel();
            //声明交换机
            channel.exchangeDeclare(DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT,true,false,null);
            // 声明队列
            channel.queueDeclare(DIRECT_QUEUE_1, true, false, false, null);
            channel.queueDeclare(DIRECT_QUEUE_2, true, false, false, null);

            //队列绑定交换机
            channel.queueBind(DIRECT_QUEUE_1,DIRECT_EXCHANGE,"error");
            channel.queueBind(DIRECT_QUEUE_2,DIRECT_EXCHANGE,"info");
            channel.queueBind(DIRECT_QUEUE_2,DIRECT_EXCHANGE,"error");
            channel.queueBind(DIRECT_QUEUE_2,DIRECT_EXCHANGE,"warning");


            String errorMsg = "error: 这是一个错误信息";
            // 发布消息
            channel.basicPublish(DIRECT_EXCHANGE,"error",null,errorMsg.getBytes());

            String infoMsg = "info: 这是一个普通信息";
            // 发布消息
            channel.basicPublish(DIRECT_EXCHANGE,"info",null,infoMsg.getBytes());

            String warningMsg = "warning: 这是一个警告信息";
            // 发布消息
            channel.basicPublish(DIRECT_EXCHANGE,"warning",null,warningMsg.getBytes());


        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                // 关闭通道
                if (channel != null & connection != null) {
                    channel.close();
                    connection.close();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

    }


}
